import {config} from './config';

const defaultHeader = (()=>{
    console.log('luban-request.ts：', config.env);
    if(config.env==='local' || window.location.hostname=='localhost'){
        const user = {};
        return {user};
    }else{
        return {}
    }
})()
export const request = {
    get : (
        url: string,
        data: any = {},
        {
            status = HttpResponseAlertStatus.FAIL,
            requestLoading = true,
            success = null,
        } = {}
    ):Promise<Result>=>{
        if(requestLoading){
            uni.showLoading({title: '加载中……',mask: true});
        }
        return new Promise((resolve,reject)=>{
            uni.request({
                url:url,
                method: 'GET',
                data:data || {},
                header: defaultHeader,
                dataType: 'json',
                success: (res) => {
                    uni.hideLoading();
                    const result = res && res.data as Result;
                    httpCallback(status, result);
                    resolve(result);
                },
                fail: (err) => {
                    uni.hideLoading();
                    uni.showToast({title:"接口请求失败"})
                    reject(err);
                }
            })
        })
    },
    post : (
        url: string,
        data: any = {},
        {
            status = HttpResponseAlertStatus.FAIL,
            requestLoading = true
        } = {}
    )=>{
        if(requestLoading){
            uni.showLoading({title: '加载中……',mask: true});
        }
        return new Promise((resolve,reject)=>{
            uni.request({
                url:url,
                method: 'POST',
                header: defaultHeader,
                data:data || {},
                success: (res) => {
                    uni.hideLoading();
                    const result = res && res.data as Result;
                    httpCallback(status, result);
                    resolve(result)
                },
                fail: (err) => {
                    uni.hideLoading();
                    uni.showToast({title:"接口请求失败"})
                    reject(err)
                }
            })
        })
    },
    put : (
        url: string,
        data: any = {},
        {
            status = HttpResponseAlertStatus.FAIL,
            requestLoading = true
        } = {}
    ):Promise<Result>=>{
        if(requestLoading){
            uni.showLoading({title: '加载中……',mask: true});
        }
        return new Promise((resolve,reject)=>{
            uni.request({
                url:url,
                method: 'PUT',
                data:data || {},
                header: defaultHeader,
                dataType: 'json',
                success: (res) => {
                    uni.hideLoading();
                    const result = res && res.data as Result;
                    httpCallback(status, result);
                    resolve(result)
                },
                fail: (err) => {
                    uni.hideLoading();
                    uni.showToast({title:"接口请求失败"})
                    reject(err)
                }
            })
        })
    },
    delete :(
        url: string,
        data: any = {},
        {
            status = HttpResponseAlertStatus.FAIL,
            requestLoading = true
        } = {}
    ):Promise<Result>=>{
        if(requestLoading){
            uni.showLoading({title: '加载中……',mask: true});
        }
        return new Promise((resolve,reject)=>{
            uni.request({
                url:url,
                method: 'DELETE',
                data:data || {},
                header: defaultHeader,
                dataType: 'json',
                success: (res) => {
                    uni.hideLoading();
                    const result = res && res.data as Result;
                    httpCallback(status, result);
                    resolve(result)
                },
                fail: (err) => {
                    uni.hideLoading();
                    uni.showToast({title:"接口请求失败"})
                    reject(err)
                }
            })
        })
    }
}
export enum HttpResponseAlertStatus {
    ALL= 1, // 无论成功失败都消息提醒
    SUCCESS= 2, // 仅成功时消息提醒
    FAIL= 3, // 仅失败时消息提醒
    NONE // 不作统一消息提醒
}

export class Result{
    constructor(public resultCode?: number,
                public resultMsg?: string,
                public data?: any
    ) {
    }

    /**
     * 是否成功返回
     * @param data
     */
    static isSuccess(data: any): boolean {
        return (data && data.isSuccess) || (data && (data.resultCode === 1 || data.resultCode === 2));
    }

    /**
     * 是否返回了失败消息
     * @param data
     */
    static isError(data: any): boolean {
        return data && data.resultMsg && data.resultCode === -1;
    }

    /**
     * 是否成功返回数组数据
     * @param data
     */
    static isArray(data: any): boolean {
        return data && data.data && Array.isArray(data.data);
    }

    /**
     * 非空数组
     * @param data：需要验证的数据
     */
    static isNotEmptyArray(data: any): boolean {
        return this.isArray(data) && data.data.length > 0;
    }

    /**
     * 是否成功返回非空对象
     * @param data
     */
    static isNotEmptyObject(data: any): boolean {
        return data && data.data;
    }
}
function httpCallback(status: HttpResponseAlertStatus, result: Result){
    if([HttpResponseAlertStatus.FAIL, HttpResponseAlertStatus.ALL].includes(status) && Result.isError(result)){
        uni.showToast({icon:'error', title:result.resultMsg  || "操作失败！", duration: 5000})
    }
    if([HttpResponseAlertStatus.SUCCESS, HttpResponseAlertStatus.ALL].includes(status) && Result.isSuccess(result)){
        uni.showToast({title:result.resultMsg  || "操作成功！", duration: 5000})
    }
}
